package com.atguigu.tingshu.common.login;


import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
@Aspect
public class TsLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    //利用反射机制+aop的环绕通知，实现是否需要登录功能

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object tsLoginAspectAround(ProceedingJoinPoint point,TsLogin tsLogin) throws  Throwable {
        //创建一个对象
        Object object = new Object();
        //如何判断一个请求是否需要登录
        //系统是如何处理登录功能
//        login(){
//            if(success){
//                key = userId; value = userInfo.toJsonString();
//                redis set key value;
//                return token;
//            }
//        }
        //从请求头中获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes=(ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        //当需要登录时，用户未登录则抛出异常，ResultCodeEnum.LOGIN_AUTH
        if (tsLogin.required()){
            //注解属性是需要登录，判断token是否为空
            if (StringUtils.isEmpty(token)){
                //未登录抛出异常
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            //token 不为空！从缓存中获取用户数据，判断用户收据是否为空
            String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
            //判断userInfo
            if (null==userInfo){
                //未登录抛出异常
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
        }

        try {
            //如果token不为空
            if (!StringUtils.isEmpty(token)){
                 //获取缓存中的数据
                String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
                //判断userInfo
                if (null != userInfo){
                    //缓存有数据： ThreadLocal
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }
            object = point.proceed();
            //返回数据
            return object;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            //调用remove()方法防止内存泄露
            AuthContextHolder.removeUserId();
        }
    }
}
